package com.zzw.springboot.service.impl;

import com.zzw.springboot.config.RabbitMQConfig;
import com.zzw.springboot.service.RabbitMQService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * RabbitMQ消息服务实现类
 */
@Service
public class RabbitMQServiceImpl implements RabbitMQService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean sendMessage(Object message) {
        try {
            // 创建唯一消息ID
            String messageId = UUID.randomUUID().toString();
            CorrelationData correlationData = new CorrelationData(messageId);

            // 添加确认回调
            final CountDownLatch latch = new CountDownLatch(1);
            final boolean[] confirmResult = {false};

            correlationData.getFuture().addCallback(
                confirm -> {
                    if (confirm.isAck()) {
                        System.out.println("消息[" + messageId + "]发送成功");
                        confirmResult[0] = true;
                    } else {
                        System.out.println("消息[" + messageId + "]发送失败: " + confirm.getReason());
                    }
                    latch.countDown();
                },
                ex -> {
                    System.out.println("消息[" + messageId + "]发送异常: " + ex.getMessage());
                    latch.countDown();
                }
            );

            // 发送消息到交换机，指定路由键
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, message, correlationData);

            // 最多等待确认结果2秒
            latch.await(2, TimeUnit.SECONDS);
            return confirmResult[0];

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
